/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package websom;

import domain.NewsArticle;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Teddy
 */
public class ParserController {

    private List<NewsArticle> newsArticles = new LinkedList<NewsArticle>();

    private static ParserController _instance = new ParserController();

    public static ParserController getInstance(){
        return _instance;
    }

    private ParserController(){
      
    }

    public void init(String pathToFolder) throws InterruptedException{

        long start = System.currentTimeMillis();
        File directory = new File(pathToFolder);
        String[] files = directory.list();

        ExecutorService service = Executors.newFixedThreadPool(5);

        for (String file : files) {
            if(file.toLowerCase().endsWith("xml")){
            service.execute(new Parser(pathToFolder, file, this));
            }
        }


        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

        service = Executors.newFixedThreadPool(20);

        for(NewsArticle newsArticle : newsArticles){
            service.execute(newsArticle);
        }

        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);
        long end = System.currentTimeMillis();
        System.out.println("Init lasted: " + (end-start));
    }

    public synchronized void addNewsArticle(NewsArticle article) {
        newsArticles.add(article);
    }

    public List<NewsArticle> getNewsArticles() {
        return newsArticles;
    }


}
